package com.smallcc.controller;

import com.lly835.bestpay.model.PayResponse;
import com.smallcc.dto.OrderDTO;
import com.smallcc.enums.ResultEnum;
import com.smallcc.exception.SellException;
import com.smallcc.service.OrderService;
import com.smallcc.service.PayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * @author 晓风过境
 * @TODO 支付的Controller
 * @date 2018/3/31 13:39
 * @day 31
 * @return $text$
 * @title ${CLASS_NAME}
 * @project_name sell
 */
@Controller
@RequestMapping("/pay")
public class PayController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private PayService payService;
    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId, @RequestParam("returnUrl") String returnUrl,
                               Map<String,Object> map){

        //查询订单
        OrderDTO orderDTO = orderService.findOne(orderId);
        if(orderDTO==null){
           throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }
        //发起支付
        PayResponse payResponse = payService.create(orderDTO);
        map.put("orderId",orderId);

        map.put("payResponse", payResponse);
        map.put("returnUrl", returnUrl);

        return new ModelAndView("pay/create", map);
    }
    //测试Freemarker是否可用
    @GetMapping("/test")
    public ModelAndView test(){
        ModelMap modelMap=new ModelMap();
        modelMap.addAttribute("name","smallchuan");
        return new ModelAndView("pay/TestFreemarker",modelMap);
    }
    @PostMapping("/notify")
    public ModelAndView notify(@RequestBody String notifyData){
        payService.notify(notifyData);
    //返回给微信处理结果
        return new ModelAndView("pay/success");
    }
}
